package ysq.xyg.base.util.httpClient;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import ysq.xyg.base.util.SpringApplicationContextUtil;
import ysq.xyg.wxapi.api.WxApiClient;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * http工具类
 */
public class HttpUtil  extends org.springframework.web.util.WebUtils{

    private final static HttpService httpService = (HttpService) SpringApplicationContextUtil.getBean("httpService");

    public static String getDomain(HttpServletRequest request){
        return request.getServerName();
    }

    public static String getHttpDomain(HttpServletRequest request){
        return request.getScheme() + "://" + request.getServerName();
    }

    public static String getContextHttpUri(HttpServletRequest request){
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    public static String getRealPath(HttpServletRequest request){
        return request.getSession().getServletContext().getRealPath("/");
    }

    public static String getRequestFullUri(HttpServletRequest request){
        String port = "";
        if(request.getServerPort() != 80){
            port = ":" + request.getServerPort();
        }
        return request.getScheme() + "://" + request.getServerName() + port + request.getContextPath() + request.getServletPath();
    }

    public static String getRequestFullUriNoContextPath(HttpServletRequest request){
        String port = "";
        if(request.getServerPort() != 80){
            port = ":" + request.getServerPort();
        }
        return request.getScheme() + "://" + request.getServerName() + port + request.getServletPath();
    }

    //获取ip地址；
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            if(ip.indexOf("::ffff:")!=-1) ip = ip.replace("::ffff:", "");
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    //判断当前请求是否为Ajax
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return !StringUtils.isEmpty(header) && "XMLHttpRequest".equals(header);
    }

    /**
     * 重定向
     * @param httpServletRequest
     * @param httpServletResponse
     * @param url
     */
    public static void redirectUrl(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String url){
        try {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重定向到http://的url
     * @param httpServletRequest
     * @param httpServletResponse
     * @param url
     */
    public static void redirectHttpUrl(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String url){
        try {
            httpServletResponse.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static JSONObject httpRequestAndReturnResult(String requestUrl, String requestMethod) {
        return httpRequestAndReturnResult(requestUrl, requestMethod, null);
    }

    /**
     *
     * 发送请求并接受响应参数
     *
     * @param requestUrl	请求地址
     * @param requestMethod 请求方式  POST GET
     * @param outputStr		请求参数
     * @return
     */
    public static JSONObject httpRequestAndReturnResult(String requestUrl, String requestMethod, String outputStr) {
        try {
            HttpResult httpResult=null;
            String result=null;
            if(StringUtils.isEmpty(outputStr)){
                if (StringUtils.equalsIgnoreCase(requestMethod,"post")){
                    httpResult = HttpUtil.httpService.doPost(requestUrl);
                    return JSONObject.parseObject(httpResult.getData());
                }else if (StringUtils.equalsIgnoreCase(requestMethod,"get")){
                    result= HttpUtil.httpService.doGet(requestUrl);
                    return JSONObject.parseObject(result);
                }
            }else{
                if (StringUtils.equalsIgnoreCase(requestMethod,"post")){
                    httpResult= HttpUtil.httpService.doPostJson(requestUrl,outputStr);
                    return JSONObject.parseObject(httpResult.getData());
                }else if (StringUtils.equalsIgnoreCase(requestMethod,"get")){
                   /* Map<String,String> hashMap= WxMessageBuilder.customTextToMap(outputStr);
                    result = HttpUtil.httpService.doGet(requestUrl,hashMap);
                    return JSONObject.fromObject(result);*/
                    return null;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * 发送请求并接受响应参数 POST
     *
     * @param requestUrl	请求地址
     * @param param		请求参数
     * @return
     */
    public static JSONObject httpRequestPost(String requestUrl, Map<String, String> param) {
        try {
            HttpResult httpResult = HttpUtil.httpService.doPost(requestUrl,param);
            return JSONObject.parseObject(httpResult.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject httpsRequestByUrlConnection(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
            System.out.print(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static byte[] httpsRequestByte(String requestUrl, String requestMethod) {
        return httpsRequestByte(requestUrl,requestMethod,null);
    }

    public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String outputStr) {
        try {
            TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            InputStream inputStream = conn.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * Xml请求
     * */
    public static String httpXml(String urlStr,String xmlInfo) {
        String result=null;
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            //con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
            //String content=new String(xmlInfo.getBytes("UTF-8"));
            //log.info("content is "+content);
            out.write(xmlInfo);
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
            String line = "";
            StringBuffer sb=new StringBuffer();
            for (line = br.readLine(); line != null; line = br.readLine()) {
                sb=sb.append(line);
            }
            result=sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * Xml请求-代码本地证书的
     * */
    public static String httpXmlClient(String urlStr, String xmlInfo){
        String result=null;
        try {
            CloseableHttpClient httpclient = WxApiClient.setLog();
            HttpPost httpost = new HttpPost(urlStr);
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(xmlInfo, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String line = "";
                    StringBuffer sb=new StringBuffer();
                    while ((line = bufferedReader.readLine()) != null) {
                        sb=sb.append(line);
                    }
                    result=sb.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

class JEEWeiXinX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}